﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SerialPortHelper
{
    public partial class Form2 : Form
    {
        //委托,子窗体发送数据给父窗体,通过父窗体的串口将数据发给下位机
        public TransmitData useForm1Send;

        //事件,子窗体发送数据给父窗体,通过父窗体的串口将数据发给下位机
        public event TransmitEventHandler useForm1Send2;


        public Form2()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 委托:从父窗体接收
        /// </summary>
        /// <param name="dataTemp"></param>
        public void ReciveData(byte[] dataTemp)
        {

            this.Invoke(new EventHandler(delegate
            {
                // 2.编码格式的选择,两个串口或者和其他单片机程序通讯,要注意两边的编码格式需要一致
                String str = Encoding.GetEncoding("gb2312").GetString(dataTemp);
                // 3. winform中RichTextBox下,对于0x00会转成\0(\0代表结束符),不会直接显示
                // 0x00 -> \0 
                str = str.Replace("\0", "\\0"); //将 "\0" 转为 "\\0",通过转义字符显示出来

                richTextBox1.AppendText(str);
            }));
        }

        /// <summary>
        /// 事件,从父窗体接收
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ReciveData2(object sender, TransmitEventArgs e)
        {
            byte[] dataTemp = e.data;

            // 2.编码格式的选择,两个串口或者和其他单片机程序通讯,要注意两边的编码格式需要一致
            String str = Encoding.GetEncoding("gb2312").GetString(dataTemp);
            // 3. winform中RichTextBox下,对于0x00会转成\0(\0代表结束符),不会直接显示
            // 0x00 -> \0 
            str = str.Replace("\0", "\\0"); //将 "\0" 转为 "\\0",通过转义字符显示出来

            MessageBox.Show(str);
        }


        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            byte[] dataTemp = Encoding.GetEncoding("gb2312").GetBytes(textBox1.Text);
            //委托调用
            useForm1Send?.Invoke(dataTemp);
            //事件调用
            useForm1Send2?.Invoke(this, new TransmitEventArgs { data = dataTemp });
        }
    }
}
